/*
* @Version: 1.1
*/

(function(global,$){
if(!$ || typeof($) !== 'function'){
    alert('jQuery is requied!');
    return;
}

//递归创建菜单树
function _createMenu(treeData_,lv_) {
    let $ul=$('<ul></ul>').addClass('menu-lv-'+lv_),$li,$p;
    if(lv_ > 1) $ul.addClass('sub-menu');//如果不是一级菜单，创建完成后直接hidn
    for (let i = 0; i < treeData_.length; i++) {
        _d = treeData_[i];
        $li = $('<li></li>').append(_createMenuTitle(_d));
        if(_d.sub && _d.sub.length) $li.append(_createMenu(_d.sub,lv_+1));//如果当前节点有子节点，递归创建
        $ul.append($li);
    };
    return $ul;
}
//创建菜单标题 p
function _createMenuTitle(d_){
    let $p = $('<p></p>').attr({id:'menu_'+d_.id,'data-url': d_.url,'data-id':d_.id,'data-pid':d_.pid,'data-lv':d_.lv,'data-name':d_.name}).addClass('menu-title');
    if (d_.url) {//菜单资源
        if (d_.icon) {
            $p.append($('<span class="glyphicon"></span>').addClass(d_.icon));
        } else{
            $p.append($('<span class="black">&nbsp;&nbsp;&nbsp;</span>'));
        };
    } else { //目录资源
        $p.append($('<span class="glyphicon glyphicon-folder-close icon-folder"></span>'));
    }
    $p.append($('<span class="name"></span>').text(d_.name));
    return $p;
}
//创建导航元素 nav > p
function _createNav($obj_){
    let $p,_id=$obj_.data('id');
    $p = $('#nav_'+_id);
    if(!$p.length) {
        $p = $('<p><span class="nav-name" title="点击切换">'+$obj_.data('name')+'</span><span class="glyphicon glyphicon-refresh refresh-this" title="点击刷新"></span><span class="glyphicon glyphicon-remove remove-this" title="点击关闭"></span></p>');
        $p.attr({id: 'nav_'+_id,'data-id':_id}).addClass('fl').addClass('nav-item');
        $('#nav').append($p);
    }
    return $p;
}
//创建框架元素 frame > p
function _createFrame($obj_){
    let $frame,_id=$obj_.data('id');
    $frame = $('#frame_'+_id);
    if(!$frame.length) {
        $frame = $('<iframe width="100%" height="100%" frameborder="0"></iframe>');
        $frame.attr({id: 'frame_'+_id,src: PATH + $obj_.data('url'),'data-id':_id}).addClass('frame-item');
        $('#frame').append($frame);
    }
    return $frame;
}

function _activeMenu(menuId_,$menu_) {

    let $menu=$menu_?$menu_:$('#menu_'+menuId_);
    if($menu.is('.active')){
        return;
    }
    $('.menu-title').removeClass('active');
    $menu.addClass('active');
    for (let i = $menu.parent().parent(); i.is('.sub-menu'); i = i.parent().parent()) {
        i.show(500);
        let $span = i.prev().find('span.icon-folder')
        if($span.is('glyphicon-folder-open')){
            $span.removeClass('glyphicon-folder-open').addClass('glyphicon-folder-close');
        }else{
            $span.removeClass('glyphicon-folder-close').addClass('glyphicon-folder-open');
        }
    };
}
//定义main页面工具的命名空间
const _main={
    heartBeatInt: 0,
    heartBeat: function(onoff) {
        let _ = this;
        if (onoff) {
            if(_.heartBeatInt) return;
            _.heartBeatInt = setInterval(function () {
                $.ajax({
                    url: PATH + '/web/heartbeat',
                    type: 'GET',
                    cache:false,
                    dataType: 'json',
                    data: {},
                    success:function(result) {
                    },
                    error:function (xmlHttpRequest, status) {
                        if(status=='error') {
                            _.heartBeat(false);
                        }
                    }
                });
            }, 5*60*1000);
        } else {
            clearInterval(_.heartBeatInt);
            _.heartBeatInt = 0;
        }
        return _;
    },
    activeMenu : function(menuId_){
        let _=this;
        _activeMenu(menuId_);
        return _;
    },
    changePassword: function(url) {
        $('#passwordForm').bootstrapValidator({
            message: 'This value is not valid',
            excluded: [":disabled"],//无需验证的
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',//显示验证成功或者失败时的一个小图标
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields:{
                oldPwd: {
                    message: '旧密码错误',//默认提示信息
                    validators: {
                        notEmpty: {
                            message: '旧密码不能为空'
                        },
                        different: {
                            field: 'newPwd', //需要进行比较的input name值
                            message: '新旧密码不能相同'
                        },
                    }
                },
                newPwd: {
                    message: '新密码错误',//默认提示信息
                    validators: {
                        notEmpty: {
                            message: '新密码不能为空'
                        },
                        stringLength: {
                            min: 6,
                            max: 10,
                            message: '密码长度为6-10位字符'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_]+$/,
                            message: '密码只能由字母、数字和下划线组成。'
                        },
                        different: {
                            field: 'oldPwd', //需要进行比较的input name值
                            message: '新旧密码不能相同'
                        },
                        identical: {
                            field: 'newPwd2',
                            message: '确认密码与新密码不一致'
                        },
                    }
                },
                newPwd2: {
                    message: '确认密码错误',
                    validators: {
                        notEmpty: {
                            message: '确认密码不能为空'
                        },
                        stringLength: {
                            min: 2,
                            max: 10,
                            message: '姓名长度不能小于2位或超过10位'
                        },
                        identical: {
                            field: 'newPwd',
                            message: '确认密码与新密码不一致'
                        },
                    }
                }
            }
        }).on('success.form.bv', function(e) {
            e.preventDefault();
            let form = $(e.target);
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: form.serialize(),
                success: function(result) {
                    if (result.code == 200) {
                        $('#pwdInfo').text('');
                        $('#passwordModal').modal('hide');
                    } else{
                        form.find("[name='oldPwd']").val('');
                        form.bootstrapValidator('validateField', 'oldPwd');
                        $('#pwdInfo').text(result.message);
                    };
                }
            });
            return false;
        });
    },
    end:0
},_menu={
    dataTree_:[],
    dataObj_:{},
    setData:function (menus) {
        let _=this;
        _.dataTree_=menus;
        return _;
    },
    ajaxData:function(url){
        let _=this;
        $.ajax({
            url: url,
            type: 'POST',
            async:false,
            cache:false,
            dataType: 'json',
            data: {},
            success:function(result){
                if (result.code==200) {
                    _.dataTree_=result.data;
                } else {
                    alert(result.message)
                }
            }
        })
        return _;
    },
    // 初始化菜单
    init : function() {
        let _=this,$menu=$('#menu');
        if (_.dataTree_ && _.dataTree_.length) {
            $menu.append(_createMenu(_.dataTree_,1));
            $menu.find('.sub-menu').hide();
        } else {
            $menu.append('<p class="no-perm">暂无任何权限</p>')
        }
        return _;
    },
    //菜单div的展开与收起
    toggleMenu : function($obj_){
        let _=this,$body=$('body'),$span = $obj_.find('span'),$nav = $('#nav_-2');
        if($body.is('.menu-show')){ //展开状态
            $span.removeClass('glyphicon-chevron-left').addClass('glyphicon-chevron-right');
            $body.removeClass('menu-show').addClass('menu-hide');
            $nav.hide();
        } else {
            $span.removeClass('glyphicon-chevron-right').addClass('glyphicon-chevron-left');
            $body.removeClass('menu-hide').addClass('menu-show');
            $nav.show();
        }
        return _;
    },
    // 子菜单的展开与收起
    toggleSub : function($obj_){
        let _=this,$span=$obj_.find('span.icon-folder');
        _activeMenu(null,$obj_);
        if(!$obj_.next().length) return _;
        if($span.length==1) $span.toggleClass('glyphicon-folder-open').toggleClass('glyphicon-folder-close');
        $obj_.next().toggle(500,function() {}, false);
        return _;
    },
    addNav : function($obj_){
        let _=this,$p,$frame;
        if(!$obj_.data('url')) return _;
        $p = _createNav($obj_);
        $p.addClass('active').siblings().removeClass('active');
        $frame = _createFrame($obj_);
        $frame.show().siblings().hide();
        return _;
    },
    removeNav : function($obj_){
        let _=this,$frame=$('#frame_'+$obj_.data('id'));
        if ($obj_.is('.active')) {
            $obj_.prev().addClass('active');
            $('#frame_'+$obj_.prev().data('id')).show();
        } else{};
        $obj_.remove();
        $frame.remove();
        return _;
    },
    removeAll : function(){
        $('#nav').find('.nav-item').remove();
        $('#frame').find('.frame-item').remove();
        $('#frame_0').show();
        $('#nav_0').addClass('active');
        $('.menu-title').removeClass('active');

    },
    toggleNav : function($obj_){
        let _=this;
        $obj_.addClass('active').siblings().removeClass('active');
        $('#frame_'+$obj_.data('id')).show().siblings().hide();
        _activeMenu($obj_.data('id'));
        return _;
    },
    refreshFrame : function($obj_){
        let _=this,$frame=$('#frame_'+$obj_.data('id'));
        $obj_.addClass('active').siblings().removeClass('active');
        $frame.attr('src', $frame.attr('src')).show().siblings().hide();
        return _;
    },
    fn : function($obj_){
        let _=this
        return _;
    },
    end:0
};

global.main = _main;
global.menu = _menu;
})(window,jQuery);

$(document).ready(function(){

    // ---事件-------
    $('#side').on('click',function(e){
        let $this = $(this);
        menu.toggleMenu($this);
    });//菜单div显示-隐藏
    $('#menu').on('click', '.menu-title', function(e) {
        let $this = $(this);
        menu.toggleSub($this);
        menu.addNav($this);
        e.preventDefault();
    });//菜单点击展开-收起子菜单

    $('#logoutModal').on('click', '.btn-danger', function(event) {
        event.preventDefault();
        window.location.href = PATH + "/logout";
    });//确认退出
    //用户信息下拉菜单-个人信息
    $('#userdrop-list').on('click', '#userinfo', function(e) {
        let $this = $(this);
        e.preventDefault();
        alert('点击用户个人信息');
    });//用户信息下拉菜单-个人信息
    $('#userdrop-list').on('click', '#password', function(e) {
        let $this = $(this);
        e.preventDefault();
        $('#passwordModal').modal('show');
    });//用户信息下拉菜单-个人信息

    $('#nav').on('click', '.nav-name', function(e) {
        let $p = $(this).parent();
        menu.toggleNav($p);
        e.preventDefault();
    });//导航栏点击激活
    $('#nav').on('click', '.remove-this', function(e) {
        let $p = $(this).parent();
        menu.removeNav($p);
        e.preventDefault();
    });//导航栏点击关闭
    $('#nav').on('click', '.refresh-this', function(e) {
        let $p = $(this).parent();
        menu.refreshFrame($p);
        e.preventDefault();
    });//导航栏点击刷新
    $('#nav').on('click', '.remove-all', function(e) {
        menu.removeAll();
        e.preventDefault();
    });//导航栏点击关闭全部
    // -------事件---
    // ---加载菜单数据-------
    menu.ajaxData(PATH+'/web/main/menu').init();
    // -- 开启心跳-------
    main.heartBeat(true);
    // -- 初始化密码修改
    main.changePassword(PATH+'/web/main/updatepassword');
});
